/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-12-15
*/
package com.rzico.article.service;

import com.rzico.article.entity.Article;
import com.rzico.article.entity.ArticleLaud;
import com.rzico.article.entity.Talent;
import com.rzico.article.model.TalentFollowVo;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.article.entity.TalentFollow;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.MemberService;
import com.rzico.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.article.mapper.TalentFollowMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * 我关注达人业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class TalentFollowService extends BaseServiceImpl<TalentFollow, String> {

    @Autowired
    private TalentFollowMapper talentFollowMapper;

    @Autowired
    private TalentService talentService;

    @Autowired
    private MemberService memberService;

    @Override
    public BaseMapper<TalentFollow, String> getMapper() {
        return talentFollowMapper;
    }


    public List<TalentFollowVo> selectTalentFollowList(Map<String, Object> params){
        return talentFollowMapper.selectTalentFollowList(params);
    }


    public List<TalentFollowVo> selectTalentFansList(Map<String, Object> params){
        return talentFollowMapper.selectTalentFansList(params);
    }

    /**
     * 添加关注的人数
     */
    @Transactional(rollbackFor = Exception.class)
    public TalentFollow addLove(Member member, TalentFollow talentFollow){
        int affectCount_self = 0;
        int affectCount = 0;
        //查看有没有这个达人
        Talent talent = talentService.findById(talentFollow.getTalentId());
        if (talent == null) {
            throw new CustomException("此达人ID不存在");
        }
        //查询自己是否是达人,不是达人的话,创建达人
        Talent talent_self = talentService.findByMember(member.getId());
        if (talent_self != null) {
            //talent_self.setModifyDate(new Date());
            talentService.updateByPrimaryKey(talent_self);
        } else {
            talent_self = new Talent();
            talent_self.setName(member.getName());
            //talent.setModifyDate(new Date());
            talent_self.setAvatar(member.getAvatar());
            //talent_self.setCreateDate(new Date());
            talent_self.setFollow(0);
            talent_self.setLove(0);
            talent_self.setMemberId(member.getId());
            affectCount_self = talentService.insertUseGeneratedKeys(talent_self);
            if (affectCount_self <= 0) {
                throw new CustomException("操作失败");
            }

        }
        //设置关注人的ID
        talentFollow.setMemberId(member.getId());
        Map<String,Object> params = new HashMap<>();
        if (talentFollow.getTalentId() != null) {
            params.put("talentId", talentFollow.getTalentId());
            params.put("memberId", talentFollow.getMemberId());
        }
        //查询数据库是否有这条记录
        List<TalentFollow> talentFollows = selectList(params);
        //follow表有关注数据,并且是取消关注
        if (talentFollows != null && talentFollows.size() != 0 && !talentFollow.getFollow()) {
            //del操作
            talentFollow = talentFollows.get(0);
            affectCount = super.deleteByPrimaryKey(talentFollow.getId());
            //此达人粉丝数减1
            if (talent.getLove() != null && talent.getLove() >= 1) {
                talent.setLove(talent.getLove()-1);
            }else if (talent.getLove() != null && talent.getLove() <= 0) {
                talent.setLove(0);
            }

            //自己关注的人数减少
            if (talent_self.getFollow() != null && talent_self.getFollow() >= 1) {
                talent_self.setFollow(talent_self.getFollow()-1);
            }else if (talent_self.getFollow() != null && talent_self.getFollow() <= 0) {
                talent_self.setFollow(0);
            }
            //follow表有关注数据,并且是关注
        } else if (talentFollows != null && talentFollows.size() != 0 && talentFollow.getFollow()){
            throw new CustomException("请勿重复关注");
            //如果follow表没数据,并且是关注
        } else if ((talentFollows == null || talentFollows.size() == 0) && talentFollow.getFollow()) {
            //没关注过,生成记录并关注,先follow表生成数据
            affectCount = super.insertUseGeneratedKeys(talentFollow);
            //操作talent数据
            if (talent.getLove() == null) {
                talent.setLove(0);
            }
            talent.setLove(talent.getLove()+1);

            //操作自己的关注人数
            if (talent_self.getFollow() == null) {
                talent_self.setFollow(0);
            }
            talent_self.setFollow(talent_self.getFollow()+1);
        } else {
            throw new CustomException("取关错误");
        }
        if (affectCount <= 0) {
            if (talentFollow.getFollow()) {
                throw new CustomException("添加关注人数错误");
            }
            throw new CustomException("取关错误");
        } else {
            //关注加1,更新表
            talentService.updateByPrimaryKey(talent);
            //自己的达人表更新
            talentService.updateByPrimaryKey(talent_self);

        }
        return talentFollow;
    }

    /**
     * 删除关注人数
     * @param talentFollow
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer decLove(TalentFollow talentFollow){
        //减少粉丝人数
        Map<String,Object> updateParams = new HashMap<>();
        updateParams.put("id", talentFollow.getTalentId());
        updateParams.put("value", 1);
        int addNum = talentService.decLvoe(updateParams);
        if (addNum <= 0) {
            throw new CustomException("删除关注人数错误");
        }

        //减少关注人数
        Map<String,Object> params = new HashMap<>();
        params.put("memberId", talentFollow.getMemberId());
        List<Talent> talentList = talentService.selectList(params);
        if (0 < talentList.size()) {
            Map<String,Object> updateFollowParams = new HashMap<>();
            updateFollowParams.put("id", talentFollow.getTalentId());
            updateFollowParams.put("value", 1);
            int followNum = talentService.decFollow(updateFollowParams);
            if (followNum <= 0) {
                throw new CustomException("添加关注人数错误");
            }
        }

        int affectCount = super.deleteByPrimaryKey(talentFollow.getId());
        if (affectCount <= 0) {
            throw new CustomException("删除关注人数错误");
        }
        return affectCount;
    }

    public boolean isFollowed(String id) {
        Member member = memberService.getCurrent();
        if (member == null) {
            return false;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", member.getId());
        params.put("talentId", id);
        List<TalentFollow> talentFollows = talentFollowMapper.selectList(params);
        if (talentFollows != null && talentFollows.size() != 0) {
            return true;
        }
        return false;
    }

    public boolean isSelf(Talent talnet) {
        Member member = memberService.getCurrent();
        if (member != null) {
            if (member.getId().equals(talnet.getMemberId()))
                return true;
        }

        return false;
    }

//    public  void followDispose(Map<String, Object> params, Member member, List<TalentFollowVo> list) {
//        //把关注自己的人的id放在一起
//        Map<Long, TalentFollowVo> memberIds = new HashMap<>();
//        list.forEach((a) ->{
//            memberIds.put(a.getMemberId(),a);
//        });
//        //根据memberIds map的条件查询出自己关注了哪些粉丝
//        Map<String, Object> followParams = new HashMap<>();
//        followParams.put("memberIds", memberIds);
//        //查出关注我的人的达人信息
//        List<Talent> talents = talentService.selectList(followParams);
//        //把关注我的人的达人id放入List
//        List<Long> talentIdList = new ArrayList<>();
//        //把talentId拿到
//        talents.forEach(a -> talentIdList.add(a.getId()));
//        //放入params
//        followParams.put("talentIds", talentIdList);
//        followParams.put("memberId", member.getId());
//        //查询出我关注的达人的id        talentFollowVos里面的达人id是自己的
//        List<TalentFollowVo> talentFollowVos = talentFollowMapper.selectMyFollowList(followParams);
//        //把我关注的达人id放入List
//        List<Long> myFolloewTalentIds = new ArrayList<>();
//        talentFollowVos.forEach(a -> myFolloewTalentIds.add(a.getTalentId()));
//        //再根据myFolloewTalentIds去查member表
//        followParams.remove("memberId");
//        followParams.put("talentIds",myFolloewTalentIds);
//        List<Long> myFollowMemberIdList = memberService.selecMemberIdByTalentIdList(followParams);
//        //将我关注的memberId转化为map
//        Map<Long, Object> collect = myFollowMemberIdList.stream().collect(Collectors.toMap(Long::valueOf, null));
//        //把查到的follow表的list和我关注的达人的memberId进行对比
//        list.forEach((a) -> {
//            if (collect.containsKey(a.getMemberId())){
//                a.setFollowFlag(true);
//            }
//        });
//    }
}
